﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SetupLauncher.Domain.Logic.Environment;
using SetupLauncher.Domain.Util;

namespace SetupLauncher.Domain.Logic
{
    public class PrepareEnvironment
    {
        private const string CONST_APP_FOLDER_BMFBOVESPA = "BMFBOVESPA";

        Logger.ILoggable _log;

        private Entity.Product _product = null;
        private Entity.Environment _env = null;

        public PrepareEnvironment(Entity.Product product, Entity.Environment environment)
        {
            Initialize(null, product, environment);
        }

        public PrepareEnvironment(Logger.ILoggable log, Entity.Product product, Entity.Environment environment)
        {
            Initialize(log, product, environment);
        }

        private void Initialize(Logger.ILoggable log, Entity.Product product, Entity.Environment environment)
        {
            _log = log;
            _product = product;
            _env = environment;

            Exceptions.ValidationException exception = new Exceptions.ValidationException();

            if (_product == null)
                exception.AddValidation(new Exceptions.Validation
                {
                    Description = "Nenhum Produto foi Informado",
                    PropertyName = "product",
                    PropertyTitle = "Produto"
                });

            if (_env == null)
                exception.AddValidation(new Exceptions.Validation
                {
                    Description = "Nenhum Ambiente foi Informado",
                    PropertyName = "environment",
                    PropertyTitle = "Ambiente"
                });

            if (exception.CountValidations > 0)
                throw exception;
        }

        public void Execute()
        {
            WriteLog("Preparando o Ambiente");
            try
            {
                try
                {
                    WriteLog(string.Format("Excluindo a pasta temporária {0}", _env.WorkSpacePath));

                    DOSCommand.Execute(string.Format("rd {0} /s /q", _env.WorkSpacePath));
                    if (!System.IO.Directory.Exists(_env.WorkSpacePath))
                        WriteLog("Pasta temporária excluída");
                    else
                        WriteLog("Não foi possível excluir a pasta temporária");    
                }
                catch(Exception ex)
                {
                    WriteLog(string.Format("Não foi possível excluir a pasta temporária. Msg {0}", ex.Message));
                }

                if (IsSystemInstalled())
                    return;

                IPrepareCommand prepare = PrepareFactory.Create(_product.Name);
                prepare.Execute();
            }
            catch (Exception ex)
            {
                WriteException(ex.Message);
                throw ex;
            }
        }

        public bool IsSystemInstalled()
        {
            WriteLog("Verifica se o ambiente deverá ser preparado antes da instalação pelo setup");

            string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData);
            path = path + @"\" + CONST_APP_FOLDER_BMFBOVESPA + @"\" + _product;
            
            return System.IO.Directory.Exists(path);

            //string[] directories = System.IO.Directory.GetDirectories(path);
            //string contains = directories.FirstOrDefault(d => d.Contains(_product));

            //return !string.IsNullOrEmpty(contains);
        }

        private void WriteLog(string message)
        {
            if (_log == null)
                return;
            _log.Write(message);
        }

        private void WriteException(string message)
        {
            if (_log == null)
                return;
            _log.WriteException(message);
        }
    }
}
